package com.dyp.security_demo.auth_handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
/**
 * 如果在访问需要权限不足的接口，默认是跳转到403页面，现在前后端分离所以不需要跳转到403页面，改成返回json信息，由前端处理！
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Autowired
    private ObjectMapper objectMapper; // Spring Boot自动配置的ObjectMapper

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        HashMap<Object,Object> result= new HashMap<>();
        result.put("code",-1);
        result.put("message", "need authorization");
        result.put("data", accessDeniedException.getLocalizedMessage());

        String json = objectMapper.writeValueAsString(result);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().println(json);
    }
}
